<?php

/**
 * user actions.
 *
 * @package    webnews
 * @subpackage user
 * @user     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userActions extends sfActions {
    public function executeIndex(sfWebRequest $request) {
	$this->users = Doctrine::getTable('user')
		->createQuery('a')
		->execute();
    }

    public function executeNew(sfWebRequest $request) {
	$this->form = new userForm();
    }

    public function executeCreate(sfWebRequest $request) {
	$this->forward404Unless($request->isMethod(sfRequest::POST));

	$this->form = new userForm();

	$this->processForm($request, $this->form);

	$this->setTemplate('new');
    }

    public function executeEdit(sfWebRequest $request) {
	$this->forward404Unless($user = Doctrine::getTable('user')->find($this->getUser()->getAttribute('id')));
	$this->form = new userForm($user);
    }

    public function executeUpdate(sfWebRequest $request) {
	$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
	$this->forward404Unless($user = Doctrine::getTable('user')->find(array($request->getParameter('id'))), sprintf('Object user does not exist (%s).', $request->getParameter('id')));
	$this->form = new userForm($user);

	$this->processForm($request, $this->form);

	$this->setTemplate('edit');
    }

    public function executeDelete(sfWebRequest $request) {
	$request->checkCSRFProtection();

	$this->forward404Unless($user = Doctrine::getTable('user')->find(array($request->getParameter('id'))), sprintf('Object user does not exist (%s).', $request->getParameter('id')));
	$user->delete();

	$this->redirect('user/index');
    }

    public function executeLogin (sfWebRequest $request) {

	// check if using RPX login
	$token = $request->getParameter('token');
	if ($token) {
	    $this->loginWithRPX($request);
	} else {
	    // TODO traditional login
	}

    }

    public function executeLogout (sfWebRequest $request) {
	$this->getUser()->setAttribute('id', 'pokus');
	$this->getUser()->setAuthenticated(false);
	$this->getUser()->shutdown();
	$this->forward('home', 'index');
    }

    protected function loginWithRPX(sfWebRequest $request) {
	$rpxApiKey = '0dca6ab376f5a4da18a8a4b04a83ac4eeacd9777';

	$token = $request->getParameter('token');

	/* Use the token to make the auth_info API call */
	$post_data = array('token' => $token,
		'apiKey' => $rpxApiKey,
		'format' => 'json');

	$curl = curl_init();
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_URL, 'https://rpxnow.com/api/v2/auth_info');
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	$raw_json = curl_exec($curl);
	curl_close($curl);


	/* Parse the JSON auth_info response */
	$auth_info = json_decode($raw_json, true);

	if ($auth_info['stat'] == 'ok') {

	    /* Extract the 'identifier' from the response */
	    $profile = $auth_info['profile'];
	    $identifier = $profile['identifier'];

	    if (isset($profile['name'])) {
		$name = $profile['name'];
	    }

	    if (isset($profile['email'])) {
		$email = $profile['email'];
	    }

	    $registered = Doctrine::getTable('User')->findOneByLogin($identifier);


	    if (!$registered) {
		$user = new User();
		$user->setLogin($identifier);
		$user->setName($name['formatted']);
		$user->save();
		$registered = Doctrine::getTable('User')->findOneByLogin($identifier);
		$first_login = true;
		// TODO Redirect to profile customization page
	    }

	    $this->getUser()->setAttribute('id',  $registered->getId());
	    $this->getUser()->setAttribute('login', $registered->getLogin());
	    $this->getUser()->setAttribute('name', $registered->getName());
	    $this->getUser()->setAuthenticated(true);
	    if($first_login) {
		$this->redirect('@profile');
	    } else {
		$this->redirect('@home');
	    }


	    /* an error occurred */
	} else {
	    // gracefully handle the error. Hook this into your native error handling system.
	    echo 'An error occured: ' . $auth_info['err']['msg'];
	}
    }


    protected function processForm(sfWebRequest $request, sfForm $form) {
	$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
	if ($form->isValid()) {
	    $user = $form->save();

	    $this->redirect('user/edit?id='.$user->getId());
	}
    }
}
